var app = new Vue({
	el: '#app',
	data: {
		id: "",
		name: "",
		roomId: "videochat",
		uservddata: {},
		myvddata: {},
		cameraType: "user",
		cameraChangeLoading: false,
		status:0
	},
	mounted(e) {
		const _this = this
		setTimeout(()=>{
			if(!_this.uservddata.id){
				uni.postMessage({
					data: {
						type: "sendFrdvdInfo",
						payload: {}
					}
				});
			}
		},5000)
	},
	onLoad(e) {
		console.log(11, e)
		const id = e.id
		this.name = this.name + "_" + id
	},
	onShow(e) {
		console.log(22, e)
	},
	methods: {
		receviceMessage: function(e) {
			console.log(e.type, e.payload)
			if(e.type == "backpress"){
				this.exit()
			}
			if (e.type == "setStreams") {
				const o = e.payload
				this.subStream({
					id: o.id ? o.id*1 : 10003,
					name: o.name,
					roomId: this.roomId,
					audio: o.audio,
					video: o.video,
					avatar:o.avatar
				})
			}
			
			
			if(e.type == "userLeave"){
				this.exit()
			}
			
			if(e.type == "userChatMuteAudio"){
				this.uservddata.audio = false
			}
			
			if(e.type == "userCharResumeAudio"){
				this.uservddata.audio = true
			}
			
			if(e.type == "userChatCloseVideo"){
				this.uservddata.video = false
			}
			
			if(e.type == "userChatOpenVideo"){
				this.uservddata.video = false
				setTimeout(() => {
					document.getElementById("vd_user").srcObject = this.uservddata.stream
				}, 500)
			}
		},
		reloadvd:function(){
			setTimeout(() => {
				document.getElementById("vd_user").srcObject = this.uservddata.stream
				document.getElementById("vd_my").srcObject = this.myvddata.stream
			}, 500)
		},
		exit: function() {
			console.log(`exit`)
			try{
				this.myvddata.unpublish()
				this.uservddata.close()
			}catch(e){
				//TODO handle the exception
			}
			uni.postMessage({
				data: {
					type: "exitmtroom",
					payload: {
			
					}
				}
			});
			uni.switchTab({
				url: "/pages/meeting/index"
			})
		},
		initData: function(e) {
			this.name = decodeURI(e.name)
			this.id = e.id
			this.roomId = e.roomId
		},
		changeCamera: function() {
			console.log(`changeCamera`)
			this.cameraChangeLoading = true
			this.cameraType = this.cameraType == "environment" ? "user" : "environment"
			this.myvddata.unpublish()
			// uni.postMessage({
			// 	data: {
			// 		type: "exitmtroom",
			// 		payload: {
			
			// 		}
			// 	}
			// });
			const _this = this
			setTimeout(() => {
				_this.cameraChangeLoading = false
				_this.publishStream({
					video: _this.myvddata.video,
					audio: _this.myvddata.audio,
					videoType: _this.cameraType
				})
			}, 1000)
		},
		muteAudio: function(type) {
			console.log(this.myvddata)
			this.myvddata.muteAudio(type)
			this.myvddata.audio = type ?? false
			if(type){
				uni.postMessage({
					data: {
						type: "resumeChatAudio",
						payload: {
							roomId:this.roomId
						}
					}
				});
			}else{
				uni.postMessage({
					data: {
						type: "muteChatAudio",
						payload: {roomId:this.roomId}
					}
				});
			}
		},
		muteVideo: function(type) {
			console.log(this.myvddata)
			this.myvddata.muteVideo(type)
			this.myvddata.video = type
			if (type) {
				uni.postMessage({
					data: {
						type: "openChatVideo",
						payload: {roomId:this.roomId}
					}
				});
				// setTimeout(() => {
				// 	document.getElementById("vd_" + this.myvddata.id).srcObject = this.myvddata
				// 		.stream
				// }, 500)
			}else{
				uni.postMessage({
					data: {
						type: "closeChatVideo",
						payload: {roomId:this.roomId}
					}
				});
			}
		},
		subStream: async function({
			id,
			name,
			roomId,
			audio,
			video,
			avatar
		}) {
			const pc = new RTCPeerConnection(null);
			pc.addTransceiver('audio', {
				direction: 'recvonly'
			});
			pc.addTransceiver('video', {
				direction: 'recvonly'
			});
			let offer = await pc.createOffer();
			let stream = new MediaStream();
			pc.ontrack = function(event) {
				console.log(event);
				stream.addTrack(event.track);
			};
			await pc.setLocalDescription(offer);
			let session = await new Promise(function(resolve, reject) {
				let data = {
					api: `https://dx11.haoleen.com/rtc/v1/play/`,
					tid: id,
					streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
					clientip: null,
					sdp: offer.sdp,
				};
				console.log('Generated offer: ', data);

				const xhr = new XMLHttpRequest();
				xhr.onload = function() {
					if (xhr.readyState !== xhr.DONE) return;
					if (xhr.status !== 200) return reject(xhr);
					const data = JSON.parse(xhr.responseText);
					console.log('Got answer: ', data);
					return data.code ? reject(xhr) : resolve(data);
				};
				xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/play/`, true);
				xhr.setRequestHeader('Content-type', 'application/json');
				xhr.send(JSON.stringify(data));
			});
			await pc.setRemoteDescription(
				new RTCSessionDescription({
					type: 'answer',
					sdp: session.sdp
				}),
			);

			function close() {
				stream.getTracks().forEach(function(track) {
					track.stop();
					stream.removeTrack(track);
				});
				// stream.close()
				pc.close();
				document.getElementById("vd_" + id).srcObject = null
			}

			const vdata = {
				id,
				roomId,
				pc,
				stream,
				name,
				avatar,
				audio: audio ?? false,
				video: video ?? false,
				close,
			};

			this.uservddata = vdata
			console.log(8888,vdata.roomId,vdata.id,stream)
			setTimeout(() => {
				document.getElementById("vd_user").srcObject = stream
			}, 1500)
		},
		publishStream: async function(options) {
			const id = this.id
			const roomId = this.roomId
			const name = this.name
			const pc = new RTCPeerConnection(null);
			pc.addTransceiver('audio', {
				direction: 'sendonly'
			});
			pc.addTransceiver('video', {
				direction: 'sendonly'
			});
			const stream = await navigator.mediaDevices.getUserMedia({
				audio: true,
				video: {
					facingMode: options.videoType ?? "environment"
				},
			});
			this.cameraType = options.videoType ?? "environment"
			console.log(stream);
			stream.getTracks().forEach(function(track) {
				pc.addTrack(track);
				// if (track.kind === 'audio') {
				// 	if (options.audio === false) {
				// 		track.enabled = false;
				// 	}
				// }
				// if (track.kind === 'video') {
				// 	if (options.video === false) {
				// 		track.enabled = false;
				// 	}
				// }
			});
			let offer = await pc.createOffer();
			await pc.setLocalDescription(offer);
			
			let session = await new Promise(function(resolve, reject) {
				let data = {
					api: `https://dx11.haoleen.com/rtc/v1/publish/`,
					tid: id,
					streamurl: `webrtc://dx11.haoleen.com/${roomId}/${id}`,
					clientip: null,
					sdp: offer.sdp,
				};
				console.log('Generated offer: ', data);

				const xhr = new XMLHttpRequest();
				xhr.onload = function() {
					if (xhr.readyState !== xhr.DONE) return;
					if (xhr.status !== 200) return reject(xhr);
					const data = JSON.parse(xhr.responseText);
					console.log('Got answer: ', data);
					if (data.code === 400) {
						resolve(false);
					}
					return data.code ? reject(xhr) : resolve(data);
				};
				xhr.open('POST', `https://dx11.haoleen.com/rtc/v1/publish/`, true);
				xhr.setRequestHeader('Content-type', 'application/json');
				xhr.send(JSON.stringify(data));
			});
			
			console.log(session);
			if (session === false) {
				return false;
			}
			await pc.setRemoteDescription(
				new RTCSessionDescription({
					type: 'answer',
					sdp: session.sdp
				}),
			);

			function muteAudio(type) {
				stream.getTracks().forEach(function(track) {
					if (track.kind === 'audio') {
						track.enabled = type ?? false;
					}
				});
			}

			function muteVideo(type) {
				stream.getTracks().forEach(function(track) {
					if (track.kind === 'video') {
						track.enabled = type ?? false;
					}
				});
			}
			const _this = this
			async function unpublish() {
				try{
					stream.getTracks().forEach(function(track) {
						track.stop();
						stream.removeTrack(track);
					});
					// stream.close()
					pc.close();
					document.getElementById("vd_" + id).srcObject = null
				}catch(e){
					//TODO handle the exception
				}
				// _this.dataList = _this.dataList.filter(e => e.id != _this.id)
				// const cid = await getPublishCidById(options.roomId, options.id);
				// console.log(cid);
				// const ret = await axios.delete(
				//   `${process.env.srsUrl}/api/v1/clients/${cid}`,
				// );
			}

			const vdata = {
				id: id,
				name: name,
				roomId: roomId,
				pc,
				stream,
				audio: options.audio == false ? false : true,
				video: options.video == false ? false : true,
				user: {
					id,
					name
				},
				muteAudio,
				muteVideo,
				unpublish: unpublish,
			};
			this.myvddata = vdata
			setTimeout(() => {
				uni.postMessage({
					data: {
						type: "pubstreamdone",
						payload: {
							id:id,
							name:name,
							roomId:roomId,
							video:vdata.video,
							audio:vdata.audio
						}
					}
				});
				document.getElementById("vd_my").srcObject = stream
			}, 1000)
		}

	}
})